package com.spsy.order.service.impl;

import com.spsy.common.core.domain.R;
import com.spsy.domain.R2;
import com.spsy.order.api.SpsyOrderProvider;
import com.spsy.order.service.OrderOpsService;
import com.spsy.order.sign.SignUtil;
import com.spsy.pay.api.SpsyPayProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: liuzhiping
 * @date: 2024/12/19 16:40
 **/
@Service
public class OrderOpsServiceImpl implements OrderOpsService {

    //雪崩、击穿、穿透
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SpsyPayProvider spsyPayProvider;

    @Override
    public R2 pay(String orderId, String userId,String productId) throws Exception{

        //标识用户的唯一的key
        String key = "order:"+userId+":"+productId;
        if(this.stringRedisTemplate.hasKey(key)){
            return R2.ok("你的订单正在处理，请3秒后再点击");
        }

        //设置key存在3秒，3秒后自动被删除
        this.stringRedisTemplate.opsForValue().set(key,"1",5, TimeUnit.SECONDS);

        //处理业务逻辑 ,如果下面处理逻辑超过3秒，麻烦了。用户可以继续下单

        Map<String,String> map = new HashMap<>();
        map.put("orderId",orderId);

        String sign = SignUtil.genSign(map,"3w24y82r4y23@","HMACSHA256");

        R2 r = this.spsyPayProvider.orderPay(orderId,sign);


        return R2.ok();
    }
}
